/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.bpmn.behavior;

import com.alibaba.fastjson2.JSONObject;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.engine.approvalnotice.ActivitiApprovalNotice;
import com.je.bpm.engine.approvalnotice.TaskApprovalNoticeEnum;
import com.je.bpm.engine.delegate.DelegateExecution;
import com.je.bpm.engine.delegate.DelegateHelper;
import com.je.bpm.engine.impl.cmd.SubmitTypeEnum;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntityImpl;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.upcoming.UpcomingCommentInfoDTO;

import java.util.List;

/**
 * 结束
 */
public class NoneEndEventActivityBehavior extends FlowNodeActivityBehavior {

    private static final long serialVersionUID = 1L;

    public static final String END_NODE = "结束节点";

    @Override
    public void execute(DelegateExecution execution) {
        completeUpcoming(execution);
        //添加审批告知
        CommandContext commandContext = Context.getCommandContext();

        List<TaskEntity> tasks = commandContext.getProcessEngineConfiguration().getTaskEntityManager()
                .findTasksByProcessInstanceId(execution.getProcessInstanceId());
        TaskEntity taskEntity;
        if (tasks.size() == 0) {
            taskEntity = ((ExecutionEntityImpl) execution).getTasks().get(0);
        } else {
            taskEntity = tasks.get(0);
        }
        addApprovalNotice(commandContext, execution, taskEntity, taskEntity.getAssignee());
        Context.getAgenda().planTakeOutgoingSequenceFlowsOperation((ExecutionEntity) execution, true);
    }


    /**
     * 待办处理
     *
     * @param execution
     */
    private void completeUpcoming(DelegateExecution execution) {
        UpcomingCommentInfoDTO upcomingInfo = DelegateHelper.buildUpcomingInfo(null, "", SubmitTypeEnum.END,
                execution.getProcessInstanceBusinessKey(), "", null);
        Context.getProcessEngineConfiguration().getActivitiUpcomingRun().completeUpcoming(upcomingInfo);
    }

    /**
     * 添加审批告知
     */
    public void addApprovalNotice(CommandContext commandContext, DelegateExecution execution, TaskEntity task, String strAssigneeUser) {
        Object variable = commandContext.getAttribute(CommandContext.APPROVALNOTICE);
        if (variable instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) variable;
            //提交人
            String assignee = jsonObject.getString("assignee");
            //审批意见
            String comment = jsonObject.getString("comment");
            //节点id
            String taskId = jsonObject.getString("taskId");
            //提交类型name
            String submitType = jsonObject.getString("submitType");
            //是否多人节点
            String isMultiStr = jsonObject.getString("isMulti");
            Boolean isMulti = Boolean.valueOf(isMultiStr);
            //审批告之事件配置类型
            List<TaskApprovalNoticeEnum> taskApprovalNoticeEnumList =
                    (List<TaskApprovalNoticeEnum>) jsonObject.get("approvalNoticeType");
            if (null == taskApprovalNoticeEnumList || taskApprovalNoticeEnumList.size() == 0) {
                return;
            }
            //多人节点从变量datas获取代办人，单人节点从task获取
            String toAssignee = END_NODE;

            String beanId = task.getBusinessKey();
            String pdId = execution.getProcessDefinitionId();
            //获取bpmnModel
            BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(pdId);
            String modelName = bpmnModel.getMainProcess().getName();
            //获取审批告知的Bean信息
            ActivitiApprovalNotice approvalNotice = commandContext.getProcessEngineConfiguration().getActivitiApprovalNotice();
            //send
            approvalNotice.sendNotice(taskApprovalNoticeEnumList, execution, assignee, comment, submitType, toAssignee, modelName, beanId);
        }
    }
}
